#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Date    : 2015-03-14 18:23:27
# @Author  : Your Name (you@example.org)
# @Link    : http://example.org
# @Version : $Id$

# from tornado_mysql import pools, connect
from pymysql import connect
from tornado import gen
from framework.db import conf
from lib import log

#为了防止IOError: [Errno 5] Input/output error,请使用False
# pools.DEBUG = False

# def ex_pool(database):
#     WX_POOL = pools.Pool(
#         dict(host=conf.host, port=conf.port, user=conf.user,passwd=conf.passwd, db=conf.database,charset='utf8'),
#         max_idle_connections=10,
#         max_recycle_sec=5)
#     return WX_POOL


# WX_POOL = pools.Pool(dict(host='114.215.130.186', port=3306, user='root',passwd='root123', db='weixin'),
#     max_idle_connections=4,
#     max_recycle_sec=5)


class BaseDb():
    def __init__(self):
        self.db=conf.database
        # self.conn = yield connect(host=conf.host, port=3306, user=conf.user, passwd=conf.passwd, db=self.db,charset='utf8')

    @gen.coroutine
    def execute(self, query, params=None):

        conn = yield connect(host=conf.host, port=3306, user=conf.user, passwd=conf.passwd, db=self.db,charset='utf8')
        cur = conn.cursor()
        count = yield cur.execute(query, params)
        rt_arr = []
        # yield conn.autocommit(True)
        for row in cur:
           rt_arr.append(row)
        # for row in cur.fetchall():
        #     print row
        cur.close()
        conn.close()
        # try:
        #     cur = yield ex_pool(self.db).execute(query, params)
        # except Exception, e:
        #     raise e
        # log.log_sql(query.strip(), params)
        raise gen.Return(rt_arr)


    @gen.coroutine
    def upd_or_ins(self, query, params=None):
        conn = yield connect(host=conf.host, port=3306, user=conf.user, passwd=conf.passwd, db=self.db,charset='utf8')
        cur = conn.cursor()
        count = yield cur.execute(query, params)
        yield conn.autocommit(True)
        cur.close()
        conn.close()
        raise gen.Return(count)

import pymysql
class MysqlDb():

    @gen.coroutine
    def execute(self, conn, query, params=None):
        # conn = pymysql.connect(host=conf.host, port=3306, user=conf.user, passwd=conf.passwd, db=self.db,charset='utf8')
        cur = conn.cursor()
        cur.execute(query, params)
        rt_arr = []
        ret = cur.fetchall()
        for row in ret:
            rt_arr.append(row)
        cur.close()
        # conn.close()
        raise gen.Return(rt_arr)